package com.yshow.common.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;


import javax.mail.internet.MimeMessage;
import java.io.File;

/**
 * Created by ruoan on 2020/9/11 17:26
 */
@Component
public class MailUtils {


    //发送者的邮箱账号
    @Value("${spring.mail.username}")
    private String mailusername;
    @Autowired
    private JavaMailSender jms;

    public String send(String mailSendTo,String mailTitle,String content){
        try {
            //建立邮件消息
            SimpleMailMessage mainMessage = new SimpleMailMessage();
            //发送者邮箱
            mainMessage.setFrom(mailusername);
            //接收者邮箱
            mainMessage.setTo(mailSendTo);
            //发送的邮件标题
            mainMessage.setSubject(mailTitle);
            //发送的内容
            mainMessage.setText(content);
            //发送
            jms.send(mainMessage);
            return "发送成功";
        }catch (Exception e){
            return "发送失败";
        }
    }

    //添加附件发送
    public String sends(String mailSendTo,String mailTitle,String content,String filePath) {
        try {
            //建立邮件消息
            MimeMessage mainMessage = jms.createMimeMessage();
            //用MimeMessageHelper组装复杂邮件，第二个参数为true，可以发送附件
            MimeMessageHelper helper = new MimeMessageHelper(mainMessage, true);
            //发送者邮箱
            helper.setFrom(mailusername);
            //接收者邮箱
            helper.setTo(mailSendTo);
            //发送的邮件标题
            helper.setSubject(mailTitle);
            //发送的内容
            helper.setText(content);
            //添加附件
            helper.addAttachment("dd.pptx", new File(filePath));
            //发送
            jms.send(mainMessage);
            return "发送成功";
        }catch (Exception e){
            return "发送失败";
        }
    }

}
